const Router = require('koa-router')
const db = require('../../db')
const path = require('path')
const fs = require('fs')
const sanitizeHtml = require('sanitize-html')

// 使用 /api/admin 前缀区分管理后台接口
const router = new Router({ prefix: '/api/admin' })

// 添加工具函数
const addTimestamp = (url) => {
  if (!url) return null;
  return `${url}?t=${Date.now()}`;
};

const removeTimestamp = (url) => {
  if (!url) return null;
  return url.split('?')[0];
};

const cleanContent = (content) => {
  if (!content) return '';
  return content
    .replace(/^<p>|<\/p>$/g, '')
    .replace(/<\/p><p>/g, '\n')
    .replace(/<[^>]+>/g, '');
};

// 获取课程列表
router.get('/courses', async (ctx) => {
  try {
    const { teacherId } = ctx.query; // 从查询参数中获取教师ID

    // 修改SQL，添加教师ID筛选条件
    const sql = `
      SELECT 
        c.*,
        cat.name as category_name,
        t.name as teacher_name,
        t.avatar as teacher_avatar,
        t.title as teacher_title
      FROM courses c
      LEFT JOIN categories cat ON c.category_id = cat.id
      LEFT JOIN teachers t ON c.teacher_id = t.id
      WHERE c.teacher_id = ?  /* 添加教师ID筛选 */
      ORDER BY c.id DESC
    `;
    
    const result = await db.query(sql, [teacherId]);
    
    const data = result.map(course => ({
      ...course,
      image_url: addTimestamp(course.image_url),
      teacher_avatar: addTimestamp(course.teacher_avatar)
    }));
    
    ctx.body = {
      code: 0,
      data,
      msg: 'success'
    };
  } catch (error) {
    console.error('获取课程列表失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 获取分类列表
router.get('/categories', async (ctx) => {
  try {
    const sql = 'SELECT * FROM categories ORDER BY sort ASC'
    const result = await db.query(sql)
    
    ctx.body = {
      code: 0,
      data: result,
      msg: 'success'
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 添加课程
router.post('/courses', async (ctx) => {
  try {
    const { 
      title, category_id, price, description, 
      image_url, tags, time_type, teacher_id 
    } = ctx.request.body

    // 确保所有参数都有默认值
    const params = [
      title || '',
      category_id || null,
      price || 0,
      description || '',
      image_url || null,
      tags || null,
      time_type || 0,
      teacher_id || null
    ]

    // 插入课程记录
    const sql = `
      INSERT INTO courses 
      (title, category_id, price, description, image_url, tags, time_type, teacher_id) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `
    
    const result = await db.query(sql, params)

    // 处理临时文件
    if (image_url && image_url.includes('temp_')) {
      // 移除时间戳查询参数
      const cleanImageUrl = removeTimestamp(image_url);
      const newImageUrl = `/uploads/images/courses/course${result.insertId}.jpg`
      const oldPath = path.join(__dirname, '../../public', cleanImageUrl)
      const newPath = path.join(__dirname, '../../public', newImageUrl)
      
      // 确保目标目录存在
      const targetDir = path.dirname(newPath)
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true })
      }
      
      // 检查源文件是否存在
      if (!fs.existsSync(oldPath)) {
        throw new Error('源文件不存在');
      }
      
      // 重命名文件
      fs.renameSync(oldPath, newPath)
      
      // 更新图片URL
      await db.query(
        'UPDATE courses SET image_url = ? WHERE id = ?',
        [newImageUrl, result.insertId]
      )
    }

    ctx.body = {
      code: 0,
      msg: 'success',
      data: { id: result.insertId }
    }
  } catch (error) {
    console.error('添加课程失败:', error)
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 更新课程
router.put('/courses/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const {
      title, category_id, price, description,
      image_url, tags, time_type, teacher_id
    } = ctx.request.body;

    // 检查课程是否属于该教师
    const checkResult = await db.query(
      'SELECT id FROM courses WHERE id = ? AND teacher_id = ?',
      [id, teacher_id]
    );

    if (checkResult.length === 0) {
      throw new Error('无权修改此课程');
    }

    // 处理新上传的图片
    if (image_url && image_url.includes('temp_')) {
      const oldResult = await db.query('SELECT image_url FROM courses WHERE id = ?', [id])
      const oldImageUrl = removeTimestamp(oldResult[0]?.image_url)
      
      const newImageUrl = removeTimestamp(image_url)
      
      // 删除原有图片
      if (oldImageUrl) {
        const oldPath = path.join(__dirname, '../../public', oldImageUrl)
        if (fs.existsSync(oldPath)) {
          fs.unlinkSync(oldPath)
        }
      }

      // 重命名新图片
      const tempPath = path.join(__dirname, '../../public', newImageUrl)
      const finalFileName = `course${id}${path.extname(newImageUrl)}`
      const newPath = path.join(__dirname, '../../public/uploads/images/courses', finalFileName)
      
      // 确保目标目录存在
      const targetDir = path.dirname(newPath)
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true })
      }

      // 检查源文件是否存在
      if (!fs.existsSync(tempPath)) {
        throw new Error('源文件不存在');
      }
      
      // 重命名文件
      fs.renameSync(tempPath, newPath)

      // 更新数据库
      const sql = `
        UPDATE courses 
        SET title = ?, category_id = ?, price = ?, 
            description = ?, image_url = ?, tags = ?, 
            time_type = ?
        WHERE id = ?
      `
      
      await db.query(sql, [
        title, category_id, price, description,
        `/uploads/images/courses/${finalFileName}`,
        tags, time_type, id
      ])
    } else {
      // 不更新图片
      const sql = `
        UPDATE courses 
        SET title = ?, category_id = ?, price = ?, 
            description = ?, tags = ?, time_type = ?
        WHERE id = ?
      `
      
      await db.query(sql, [
        title, category_id, price, description,
        tags, time_type, id
      ])
    }

    ctx.body = {
      code: 0,
      msg: 'success'
    }
  } catch (error) {
    console.error('更新课程失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
})

// 删除课程
router.delete('/courses/:id', async (ctx) => {
  let connection;
  try {
    const { id } = ctx.params;
    const { teacherId } = ctx.query; // 从查询参数中获取教师ID

    if (!id || !teacherId) {
      throw new Error('缺少必要参数');
    }

    connection = await db.beginTransaction();

    // 先检查课程是否属于该教师
    const checkResult = await db.query(
      'SELECT id FROM courses WHERE id = ? AND teacher_id = ?',
      [id, teacherId],
      connection
    );

    if (checkResult.length === 0) {
      throw new Error('无权删除此课程');
    }

    // 获取课程信息
    const result = await db.query(
      'SELECT image_url FROM courses WHERE id = ?', 
      [id], 
      connection
    );
    const imageUrl = result[0]?.image_url;

    // 删除课程章节
    await db.query(
      'DELETE FROM course_schedules WHERE course_id = ?', 
      [id], 
      connection
    );

    // 删除课程记录
    await db.query(
      'DELETE FROM courses WHERE id = ?', 
      [id], 
      connection
    );

    await db.commit(connection);

    // 删除课程图片
    if (imageUrl) {
      const imagePath = path.join(__dirname, '../../public', imageUrl);
      if (fs.existsSync(imagePath)) {
        fs.unlinkSync(imagePath);
      }
    }

    ctx.body = {
      code: 0,
      msg: 'success'
    };
  } catch (error) {
    if (connection) {
      await db.rollback(connection);
    }
    console.error('删除课程失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 添加文件上传路由
router.post('/upload', async (ctx) => {
  try {
    const file = ctx.request.files?.file
    if (!file) {
      throw new Error('没有上传文件')
    }

    // 确保上传目录存在
    const uploadDir = path.join(__dirname, '../../public/uploads/images/courses')
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true })
    }

    // 生成临时文件名
    const ext = path.extname(file.originalFilename || '')
    const fileName = `temp_${Date.now()}${ext}`
    const targetPath = path.join(uploadDir, fileName)

    // 移动文件
    fs.renameSync(file.filepath, targetPath)

    // 返回带时间戳的URL
    const url = addTimestamp(`/uploads/images/courses/${fileName}`)

    ctx.body = {
      code: 0,
      msg: 'success',
      url
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 获取课程章节
router.get('/courses/:courseId/schedules', async (ctx) => {
  try {
    const { courseId } = ctx.params;
    
    // 直接查询课程所属的教师ID
    const sql = `
      SELECT id, title, content, sort
      FROM course_schedules
      WHERE course_id = ?
      ORDER BY sort ASC
    `;
    
    const result = await db.query(sql, [courseId]);
    
    ctx.body = {
      code: 0,
      data: result,
      msg: 'success'
    };
  } catch (error) {
    console.error('获取课程章节失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 更新课程章节
router.put('/courses/:courseId/schedules', async (ctx) => {
  let connection;
  try {
    const { courseId } = ctx.params;
    const { schedules } = ctx.request.body;

    // 开启事务
    connection = await db.beginTransaction();

    // 删除原有章节
    await db.query('DELETE FROM course_schedules WHERE course_id = ?', [courseId], connection);

    // 插入新章节，保留HTML格式
    for (const schedule of schedules) {
      const sql = `
        INSERT INTO course_schedules (course_id, title, content, sort)
        VALUES (?, ?, ?, ?)
      `;
      
      // 对HTML内容进行安全处理
      const safeContent = schedule.content ? sanitizeHtml(schedule.content, {
        allowedTags: [ 
          'p', 'b', 'i', 'em', 'strong', 'u', 
          'ul', 'ol', 'li', 'br'
        ],
        allowedAttributes: {},
      }) : '';

      await db.query(sql, [courseId, schedule.title, safeContent, schedule.sort], connection);
    }

    // 提交事务
    await db.commit(connection);

    ctx.body = {
      code: 0,
      msg: 'success'
    };
  } catch (error) {
    // 回滚事务
    if (connection) {
      await db.rollback(connection);
    }
    console.error('更新课程章节失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

module.exports = router 